import {
	query,
	CollectionSchema,
	Collection2Schema,
	getTopStaff,
	getKuCun,
} from '@/common/getData';
import setLatestDate from '@/common/setLastestDate';

export default async function fetchData() {
	const dataPool = {};
	// 查询工单类数据
	const schema1 = CollectionSchema();
	const latestDateRs = await query('kuandai_zt', 'action/getLatestDate');
	// console.log('latestDate', latestDate);
	const dateBefore = latestDateRs.data[0].date;
	const dateAfter = dateBefore - 60;
	const dateRange = {
		$or: [
			{
				date: {
					$gte: window.NLObj.prevYearDays[0],
					$lte: window.NLObj.prevYearDays.slice(-1)[0],
				}
			},
			{
				date:
				{
					$gte: window.NLObj.thisYearDays[0],
					$lte: window.NLObj.thisYearDays.slice(-1)[0],
				}
			},
			{
				date:
				{
					$gte: dateAfter,
					$lte: dateBefore,
				}
			},
		]
	}
	const promises = Object.keys(schema1).map(async (collection) => {
		const bizField = schema1[collection];
		for (const biz of Object.keys(bizField)) {
			const data = await query(collection, 'action/getList', { [biz]: '是', ...dateRange });
			schema1[collection][biz] = data;
		}
		const allBizData = await query(collection, 'action/getList', dateRange);
		schema1[collection]['all'] = allBizData;
		return schema1[collection];
	});

	await Promise.all(promises);

	console.log('dataPool 1', schema1);
	setLatestDate(schema1);
	window.dataPool.dataPool1 = dataPool.dataPool1 = schema1;

	//查询指标类数据
	const schema2 = Collection2Schema();
	await Promise.allSettled(
		Object.keys(schema2).map(async (collection) => {
			const data = await query(collection, 'action/getList2');
			schema2[collection] = data;
			return schema1[collection];
		})
	);

	console.log('dataPool 2', schema2);
	window.dataPool.dataPool2 = dataPool.dataPool2 = schema2;

	const topStaff = {};
	let params = [
		{
			collection: 'kuandai_zt',
			limit: 30,
			fields: [
				{ name: 'chaochang', value: '是' },
				{ name: 'yujing', value: '是' },
			],
		},
		{
			collection: 'xinyewu_zt',
			limit: 30,
			fields: [
				{ name: 'chaochang', value: '是' },
				{ name: 'yujing', value: '是' },
			],
		},
		{
			collection: 'tousu_zt',
			limit: 30,
			fields: [
				{ name: 'chaochang', value: '是' },
				{ name: 'yujing', value: '是' },
				{ name: 'vip', value: '是' },
			],
		},
	];
	await Promise.allSettled(
		params.map(async (param) => {
			topStaff[param.collection] = await getTopStaff(param);
		})
	);
	dataPool.topStaff = topStaff;
	console.log('topStaff', topStaff);

	dataPool.kuCun = await getKuCun();
	console.log('KuCun', dataPool.kuCun);

	return dataPool;
}
